const { connection } = require("../base/connect");
const { throwError } = require("../base/error");
const { sendData } = require("../base/success");
module.exports = async (ctx) => {
  let collection = (await connection).collection("news");
  let result;
  if (typeof ctx.query["id"] === "undefined") {
    result = await collection.find().toArray();
  } else {
    const news_id = parseInt(ctx.query.id);
    if (!Number.isFinite(news_id) || news_id < 100000 || news_id > 1000000) {
      throwError(ctx, -1, "参数错误");
      return;
    }
    if (!news_id) result = await collection.find().toArray();
    else {
      result = await collection.find({ id: news_id }).toArray();
      if (!result.length) {
        throwError(ctx, 0, "新闻不存在~");
        return;
      }
    }
  }
  sendData(ctx, result);
};
